
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class TencentCos {

    // 存储桶名称
    private static final String BUCKET_NAME = "BUCKET_NAME";
    //secretId 秘钥id
    private static final String SECRET_ID = "SECRET_ID";
    //SecretKey 秘钥
    private static final String SECRET_KEY = "SECRET_KEY";
    // 访问域名
    public static final String URL = "https://{BUCKET_NAME}.cos.ap-shanghai.myqcloud.com";
    // 创建COS 凭证
    private static final COSCredentials credentials = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
    // 配置 COS 区域 就购买时选择的区域 我这里是 南京（nanjing）
    private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));

    /**
     * 上传文件
     */
    public static String uploadFile(MultipartFile file, String path, String fileName) {
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials, clientConfig);
        try {
            assert fileName != null;

            InputStream inputStream = file.getInputStream();
            String key = path + "/" + fileName;

            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储，需要设置请求长度
            objectMetadata.setContentLength(inputStream.available());
            // - 设置缓存
            objectMetadata.setCacheControl("no-cache");
            // - 设置Content-Type
            objectMetadata.setContentType(FilenameUtils.getExtension(fileName));
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, inputStream, objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            return URL + "/" + key;
        } catch (IOException e) {
            log.error("TencentCos-uploadFile-Error:", e);
            return "";
        } finally {
            cosClient.shutdown();
        }
    }

}
